<?php

namespace App\Http\Controllers\Admin;

use App\Models\AdminUser;
use App\Models\Permission;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Spatie\Permission\Models\Role;

class RoleController extends Controller
{
    protected $guard_name = 'web';
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $username = Session::get('admin.username');
        $user = AdminUser::where(['username'=>$username]) -> first();
        /*dump($user->getAllPermissions());//所有权限
        dump($user->can('role'));//验证单个权限
        dump($user->getDirectPermissions());//
        dump($user->getPermissionsViaRoles());*/
//      dump($user->hasAnyPermission(['adminuser', 'adminuser.edit', 'adminuser.update']));//多个权限验证

        $page = Role::with('permissions')->paginate(10);
        if($page)
        {
            foreach($page as &$item)
            {
                $permission = [];
                if($item->permissions)
                {
                    foreach($item->permissions as $per)
                    {
                        $permission[] = $per['describe'];
                    }
                }
                $item->permission = $permission;
            }
        }
        return view('Admin.Role.index',compact('page'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $permission = Permission::where([['pid','=',0],['id','>',1]])
            ->with(['subPermissions'=>function($query){
                $query->with('subPermissions');
            }])
            ->get();
        return view('Admin.Role.create',compact('permission'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $exist = Role::where(['name'=>$request->roleName])
            ->first();
        if(!$exist) {
            $res = Role::create(['name' => $request->roleName, 'guard_name' => $this->guard_name, 'describe' => $request->describe]);
            if ($res) {
                if($request->permission)
                {
                    /*将权限绑定到角色*/
                  /* foreach($request->permission as $item)
                    {
                      $permissions = \Spatie\Permission\Models\Permission::where(['name'=>$item])
                                     ->first();
                        $permissions -> assignRole($res->id);//角色添加权限
                        $permissions -> syncRoles($res->id);//刷新

                    }*/
                    $res->givePermissionTo($request->permission);
                }
            }
        }else{
            $this->set('code',1);
            $this->set('message','已经存在');
        }
        return $this->ajaxResponse();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $permission = Permission::where([['pid','=',0],['id','>',1]])
            ->with(['subPermissions'=>function($query){
                $query->with('subPermissions');
            }])
            ->get();
        $show = Role::with('permissions')->find($id);
        $pers = [];
        if($show)
        {
            foreach($show->permissions as $item)
            {
                $pers[] = $item->name;
            }
        }
//        dump($pers);

        return view('Admin.Role.edit',compact(['permission','pers','show']));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //修改前：
        $role = Role::with('permissions')->find($id);
        $pers = [];
        if($role)
        {
            foreach($role->permissions as $item)
            {
                $pers[] = $item->name;
            }
        }
        //权限更新
        if($request->permission) {
            $role->revokePermissionTo($pers);
            $role->givePermissionTo($request->permission);
            Role::where(['id'=>$id])->update(['describe'=> $request->describe ? $request->describe :$role->describe ]);
        }
        else{
            $this->set('code',1);
            $this->set('message','输入错误');
        }
        return $this->ajaxResponse();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
//        $role = Role::findById($id);
//        if($role){
//          /*  DB::beginTransaction();
//            try{
//                Role::destroy($id);
//                AdminUser::where(['role'=>$exist->name])->update(['status'=>0]);
//                DB::commit();
//            }
//            catch (\Exception $e){
//                DB::rollback();//事务回滚
//                $this->set('code',1);
//                $this->set('message','修改失败');
//            }*/
//        }else{
            $this->set('code',1);
            $this->set('message','角色不能删除，请直接编辑');
//        }
        return $this->ajaxResponse();
    }
}
